// 引入axios
import promise from 'es6-promise'
import axios from 'axios'
import localStorage from '../storage/localStorage'
promise.polyfill()

const service = axios.create({
  timeout: 20000 // 请求超时 20s
})

// 请求拦截器
service.interceptors.request.use(config => {
  // 是否为当前的请求加上请求头 token
  if (localStorage.get('token')) {
    config.headers['x-auth-token'] = localStorage.get('token')
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    return response
  },
  error => {
    // 失败响应
    if (error && error.response) {
      let res = error.response.data
      if (Number(res.errCode) === 1002) {
        // 跳转登录路由.
        localStorage.remove('token')
      } else {
        return Promise.reject(error.response)
      }
    }
  }
)
export default service
